<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>


<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">



  <meta name="description" content="如何用Tkinter写个计算器"/>




  <meta name="keywords" content="python, tkinter, 八一" />



  <meta name="baidu-site-verification" content="HhUstaSjr0" />



  <meta name="google-site-verification" content="UA-102975942-1" />






  <link rel="alternate" href="/atom.xml" title="八一">




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=2.6.0" />



<link rel="canonical" href="https://bay1.top/2017/12/08/如何用Tkinter写个计算器/"/>


<link rel="stylesheet" type="text/css" href="/css/style.css?v=2.6.0" />
<link rel="stylesheet" type="text/css" href="/css/prettify.css" media="screen" />
<link rel="stylesheet" type="text/css" href="/css/sons-of-obsidian.css" media="screen" />



  <link rel="stylesheet" type="text/css" href="/lib/fancybox/jquery.fancybox.css" />




  
  <script id="baidu_analytics">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?9a885cc9fb6cd7bcef579deb8efe8a70";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>



  <script id="google_analytics">
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

        ga('create', 'UA-102975942-1', 'auto');
        ga('send', 'pageview');
  </script>










    <title> 如何用Tkinter写个计算器 - 八一 </title>
  </head>

  <body><div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/." class="logo">八一</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>

<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    
      <a href="/archives">
        <li class="mobile-menu-item">
          
          
            文章
          
        </li>
      </a>
    
      <a href="/tags">
        <li class="mobile-menu-item">
          
          
            标签
          
        </li>
      </a>
    
      <a href="/about">
        <li class="mobile-menu-item">
          
          
            关于/友链
          
        </li>
      </a>
    
      <a href="/search">
        <li class="mobile-menu-item">
          
          
            站内搜索
          
        </li>
      </a>
    
  </ul>
</nav>

    <div class="container" id="mobile-panel">
      <header id="header" class="header"><div class="logo-wrapper">
  <a href="/." class="logo">八一</a>
</div>

<nav class="site-navbar">
  
    <ul id="menu" class="menu">
      
        <li class="menu-item">
          <a class="menu-item-link" href="/archives">
            
            
              文章
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/tags">
            
            
              标签
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/about">
            
            
              关于/友链
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/search">
            
            
              站内搜索
            
          </a>
        </li>
      
    </ul>
  
</nav>

      </header>

      <main id="main" class="main">
        <div class="content-wrapper">
          <div id="content" class="content">
            
  
  <article class="post">
    <header class="post-header">
      <h1 class="post-title">
        
          如何用Tkinter写个计算器
        
      </h1>

      <div class="post-meta">
        <span class="post-time">
          2017-12-08
        </span>
        
        
        
      </div>
    </header>

    
    
  <div class="post-toc" id="post-toc">
    <h2 class="post-toc-title">文章目录</h2>
    <div class="post-toc-content">
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#开始一个窗口"><span class="toc-text">开始一个窗口</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#面板显示"><span class="toc-text">面板显示</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#按钮-输入框设置"><span class="toc-text">按钮,输入框设置</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#输入限制"><span class="toc-text">输入限制</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#拓展符号设计"><span class="toc-text">拓展符号设计</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#关于lambda"><span class="toc-text">关于lambda</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#关于单选框"><span class="toc-text">关于单选框</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#打包"><span class="toc-text">打包</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#效果预览"><span class="toc-text">效果预览</span></a></li></ol>
    </div>
  </div>


    <div class="post-content">
      
        <p>上机实践课程开始了,嗯，老师来了之后念了下PPT，然后说:开始做吧………<a id="more"></a><br>ennnn……..就先别管老师怎么教了，PPT标注了可以不限语言</p>
<blockquote>
<p>然后就开始了Python的GUI之路，以前没接触过PYthon的可视化界面(虽然这样很不明智)<br>但是现在做起来感觉写小工具还挺方便的，当时搜到的第一个库便是Tkinter就直接开始写了<br>后来发现QT很不错的样子，下个实验就用QT吧.然后关于Tkinter(python3.6)</p>
</blockquote>
<p><a href="https://github.com/bayi27/Integrated-practice-of-programming-/tree/master/Calculator" target="_blank" rel="noopener">计算器源码</a> ennn…..有的命名不规范…….</p>
<blockquote>
<p>首先对于python中栈的实现是通过list的方式模拟<br>pop()出栈，append()入栈</p>
</blockquote>
<h2 id="开始一个窗口"><a href="#开始一个窗口" class="headerlink" title="开始一个窗口"></a>开始一个窗口</h2><blockquote>
<p>做一个可视化的东西，首先想到的坑定是窗口吧<br>窗口又有很多构成，比如title,ico，size,bd,菜单等.</p>
</blockquote>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> tkinter</span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Calculator</span><span class="params">(object)</span>:</span></span><br><span class="line">	<span class="string">"""计算器"""</span></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">		self.tk=tkinter.Tk() <span class="comment">#实例化</span></span><br><span class="line">		self.tk.title(<span class="string">'计算器'</span>)</span><br><span class="line">		self.tk.minsize(<span class="number">370</span>,<span class="number">460</span>)</span><br><span class="line">		self.tk.maxsize(<span class="number">400</span>,<span class="number">400</span>)</span><br><span class="line">		<span class="comment">#也可以用self.tk.resizable(0, 0)来禁止调节大小</span></span><br><span class="line">		self.tk.iconbitmap(os.getcwd()+<span class="string">'/favicon.ico'</span>)</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">start</span><span class="params">(self)</span>:</span></span><br><span class="line">		self.tk.mainloop()	</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">	NewCalculator=Calculator()</span><br><span class="line">	NewCalculator.start()</span><br></pre></td></tr></table></figure>
<p>这里就生成了一个基本的窗口,对于其中的mainloop()的作用<br>如果我们删除它,窗口会一闪而过，它就是为了防止这种情况</p>
<h2 id="面板显示"><a href="#面板显示" class="headerlink" title="面板显示"></a>面板显示</h2><p>做成计算器之后坑定要先是计算结果，这里就需要生成显示面板<br>当然我们也会很自然地联想到显示内容的字体设置等需求，具体事例在下面代码</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">....</span><br><span class="line"><span class="keyword">import</span> tkinter.font <span class="keyword">as</span> tkfont</span><br><span class="line"></span><br><span class="line">....</span><br><span class="line">		<span class="comment">#字体设置</span></span><br><span class="line">		self.EntryFont=tkfont.Font(self.tk,size=<span class="number">13</span>)</span><br><span class="line">		self.ButtonFont=tkfont.Font(self.tk,size=<span class="number">12</span>)</span><br><span class="line">		<span class="comment">#面板显示</span></span><br><span class="line">		self.count=tkinter.StringVar()</span><br><span class="line">		self.count.set(<span class="string">'0'</span>)</span><br><span class="line">		self.label=tkinter.Label(self.tk,bg=<span class="string">'#EEE9E9'</span>,bd=<span class="string">'3'</span>,fg=<span class="string">'black'</span>,anchor=<span class="string">'center'</span>,font=self.EntryFont,textvariable=self.count)</span><br><span class="line">		self.label.place(y=<span class="number">10</span>,width=<span class="number">380</span>,height=<span class="number">40</span>)</span><br><span class="line"></span><br><span class="line">....</span><br></pre></td></tr></table></figure>
<blockquote>
<p>其中tkinter中面板Lable有一些参数，这里用到的基本上也可以满足常见的需求了<br>其中bg是背景色，fg是前景色，改变内容的颜色，anchor是定位内容在面板中的位置，如下图</p>
</blockquote>
<table>
<thead>
<tr>
<th>方向</th>
<th>示例</th>
<th>表格</th>
</tr>
</thead>
<tbody>
<tr>
<td>nw</td>
<td>n</td>
<td>ne</td>
</tr>
<tr>
<td>w</td>
<td>center</td>
<td>e</td>
</tr>
<tr>
<td>sw</td>
<td>s</td>
<td>se</td>
</tr>
</tbody>
</table>
<p>关于面板以及后边的Button的定位，可以用很多方式，place可以准确的定位，也可以用pack(),grid()<br>对于计算器place是更好的，能够准确定位每一个控件<br>其中字体也可以直接在Lable()加参数，例如font=(“Arial,6”)<br>textvariable相当于“监听”的作用，绑定tkinter中的string，就可以用set()的方式方便的改变面板的内容</p>
<h2 id="按钮-输入框设置"><a href="#按钮-输入框设置" class="headerlink" title="按钮,输入框设置"></a>按钮,输入框设置</h2><p>按钮,输入框的参数和面板里面的是相似的</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">self.NumButton=tkinter.Button(master=self.tk,relief=GROOVE,bg=<span class="string">'#EE6A50'</span>,text=self.ButtonList[<span class="number">0</span>],</span><br><span class="line">			font=self.ButtonFont,command=self.clear)</span><br><span class="line">self.NumButton.place(x=<span class="number">30</span>,y=<span class="number">80</span>,width=<span class="number">70</span>,height=<span class="number">55</span>)</span><br><span class="line"></span><br><span class="line">self.shiEntry=Entry(self.baoxianTk,validate=<span class="string">'key'</span>,validatecommand=(self.checkNum,<span class="string">'%P'</span>),font=self.EntryFont)</span><br><span class="line">self.shiEntry.place(x=<span class="number">190</span>,y=<span class="number">80</span>)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>一样的是通过bg等参数设置基础的样式，只不过这里会通过command绑定事件，类似于JQ中的.click<br>这里的place也是为了能够准确定位才使用的，其中的relief代表着Button的样式<br>relief=FLAT or GROOVE or RAISED or RIDGE or SOLID or SUNKEN</p>
</blockquote>
<p>其中删除输入框的输入内容</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">text.delete(<span class="number">10</span>)  <span class="comment">#删除索引值为10的值</span></span><br><span class="line">text.delete(<span class="number">10</span>, <span class="number">20</span>)  <span class="comment">#删除索引值从10到20之前的值</span></span><br><span class="line">text.insert(<span class="number">0</span>, END)  <span class="comment">#删除所有值</span></span><br></pre></td></tr></table></figure>
<h2 id="输入限制"><a href="#输入限制" class="headerlink" title="输入限制"></a>输入限制</h2><p>在设计功能的时候我们可能需要用户输入数字等，这里可以进行限制一下<br>Button参数中validate指定什么时候执行validatecommand绑定的函数，使用%P可以实时获取输入的内容<br>当validate选项指定为key的时候，有任何的输入操作都会被拦截,这个时候返回True白能量才会输入到Entry</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">self.checkNum=self.baoxianTk.register(self.validateNum)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">self.gerenEntry=Entry(self.baoxianTk,validate=<span class="string">'key'</span>,validatecommand=(self.checkNum,<span class="string">'%P'</span>),font=self.EntryFont)</span><br><span class="line">self.gerenEntry.place(x=<span class="number">190</span>,y=<span class="number">190</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">#验证是否输入数字	</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">validateNum</span><span class="params">(self,content)</span>:</span></span><br><span class="line">	<span class="keyword">if</span> content.isdigit() <span class="keyword">and</span> int(content)&gt;=<span class="number">0</span> <span class="keyword">or</span> content==<span class="string">""</span>:</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">True</span></span><br><span class="line">	<span class="keyword">else</span>:</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">False</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>validateNum()函数可以根据自己的需求进行更改<br>启用验证validate选项可以设置的值有：</p>
</blockquote>
<table>
<thead>
<tr>
<th>名称</th>
<th>事件</th>
</tr>
</thead>
<tbody>
<tr>
<td>focus</td>
<td>当 Entry 组件获得或失去焦点的时候验证</td>
</tr>
<tr>
<td>focusin</td>
<td>当 Entry 组件获得焦点的时候验证</td>
</tr>
<tr>
<td>focusout</td>
<td>当 Entry 组件失去焦点的时候验证</td>
</tr>
<tr>
<td>key</td>
<td>当输入框被编辑的时候验证</td>
</tr>
<tr>
<td>all</td>
<td>当出现上边任何一种情况的时候验证</td>
</tr>
</tbody>
</table>
<h2 id="拓展符号设计"><a href="#拓展符号设计" class="headerlink" title="拓展符号设计"></a>拓展符号设计</h2><p>这个小计算器中我增加了%，/，sqrt三个符号<br>对于他们的实现我的思路是添加到面板之前检测一下传入的button内容<br>如果是这三种符号则做出对应的处理</p>
<blockquote>
<p>其中需要注意如果是多位数或者带有符号式子<br>不能直接进行变换，需要判断你要转置的数字的位数，我的具体方式如下</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">checkList</span><span class="params">(self)</span>:</span></span><br><span class="line">	result=<span class="number">0</span></span><br><span class="line">	locate=<span class="number">-1</span></span><br><span class="line">	listSum=<span class="number">0</span></span><br><span class="line">	<span class="keyword">for</span> length <span class="keyword">in</span> range(<span class="number">0</span>,len(self.inputlist)):</span><br><span class="line">		<span class="keyword">if</span> re.findall(<span class="string">r'[-+*/]'</span>,str(self.inputlist[length])):</span><br><span class="line">			result=<span class="number">1</span></span><br><span class="line">			<span class="keyword">if</span> length&gt;locate:</span><br><span class="line">				locate=length</span><br><span class="line">		<span class="keyword">else</span>:</span><br><span class="line">			<span class="keyword">pass</span></span><br><span class="line">	<span class="keyword">if</span> result==<span class="number">1</span>:</span><br><span class="line">		<span class="keyword">for</span> i <span class="keyword">in</span> range(locate+<span class="number">1</span>,len(self.inputlist)):</span><br><span class="line">			listSum+=int(self.inputlist[i])*(<span class="number">10</span>**(len(self.inputlist)-i<span class="number">-1</span>))</span><br><span class="line">	<span class="keyword">else</span>:</span><br><span class="line">		<span class="keyword">for</span> j <span class="keyword">in</span> range(<span class="number">0</span>,len(self.inputlist)):</span><br><span class="line">			listSum+=int(self.inputlist[j])*(<span class="number">10</span>**(len(self.inputlist)-j<span class="number">-1</span>))</span><br><span class="line">	<span class="keyword">return</span> listSum,locate</span><br><span class="line"><span class="comment">#添加button</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">addButton</span><span class="params">(self,button)</span>:</span></span><br><span class="line">	<span class="keyword">if</span> button==self.ButtonList[<span class="number">18</span>]:</span><br><span class="line">		listSum,locate=self.checkList()</span><br><span class="line">		<span class="keyword">if</span> locate==<span class="number">-1</span>:</span><br><span class="line">			self.inputlist=[str(round(eval(<span class="string">'1/'</span>+str(listSum)),<span class="number">5</span>))]</span><br><span class="line">		<span class="keyword">else</span>:</span><br><span class="line">			<span class="keyword">for</span> k <span class="keyword">in</span> range(locate+<span class="number">1</span>,len(self.inputlist)):</span><br><span class="line">				<span class="keyword">del</span> self.inputlist[k]</span><br><span class="line">			self.inputlist.append(str(round(eval(<span class="string">'1/'</span>+str(listSum)),<span class="number">5</span>)))</span><br><span class="line">	<span class="keyword">elif</span> button==self.ButtonList[<span class="number">19</span>]:</span><br><span class="line">		<span class="keyword">pass</span></span><br><span class="line">	<span class="keyword">elif</span> button==self.ButtonList[<span class="number">20</span>]:</span><br><span class="line">		<span class="keyword">pass</span></span><br><span class="line">	<span class="keyword">else</span>:</span><br><span class="line">		self.inputlist.append(button)</span><br><span class="line">	self.count.set(self.inputlist)</span><br></pre></td></tr></table></figure>
<h2 id="关于lambda"><a href="#关于lambda" class="headerlink" title="关于lambda"></a>关于lambda</h2><blockquote>
<p>百度百科：Lambda表达式是Python中一类特殊的定义函数的形式，使用它可以定义一个匿名函数<br>与其它语言不同，Python的Lambda表达式的函数体只能有唯一的一条语句，也就是返回值表达式语句</p>
</blockquote>
<p>搜索更多文章后理解更多，Lambda函数可以说是对按钮起到“call back”的作用<br>如果我们不使用Lambda进行中间函数的延迟回调，在创建按钮的同时command绑定的函数会被调用<br>即如下面两句代码的区别,第二句在进行创建时会直接执行knobDown函数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">self.NumButton=tkinter.Button(master=self.tk,relief=GROOVE,bg=<span class="string">'#BFEFFF'</span>,text=self.ButtonList[<span class="number">20</span>],</span><br><span class="line">			font=self.ButtonFont,command=<span class="keyword">lambda</span>:self.knobDown(self.ButtonList[<span class="number">20</span>]))</span><br><span class="line">self.NumButton=tkinter.Button(master=self.tk,relief=GROOVE,bg=<span class="string">'#BFEFFF'</span>,text=self.ButtonList[<span class="number">20</span>],</span><br><span class="line">			font=self.ButtonFont,command=self.knobDown(self.ButtonList[<span class="number">20</span>]))</span><br></pre></td></tr></table></figure>
<blockquote>
<p>更详细的解释可以参考文末最后两个文章，还是前辈写得好</p>
</blockquote>
<h2 id="关于单选框"><a href="#关于单选框" class="headerlink" title="关于单选框"></a>关于单选框</h2><p>本来想实现PPT中给出的示例-房贷计算的拓展，但是一直这个单选框产生BUG就放弃了<br>下面的示例是从网上摘抄过来的，具体的网址忘了<br>就是通过variable绑定一个IntVar(),通过.get()方式可以获取Radiobutton中value的值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#!/usr/bin/env python</span></span><br><span class="line"><span class="keyword">import</span> tkinter</span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">import</span> tkinter.font <span class="keyword">as</span> tkfont</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">root=tkinter.Tk()</span><br><span class="line"></span><br><span class="line">val=tkinter.IntVar()</span><br><span class="line"></span><br><span class="line">val.set(<span class="number">0</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">func1</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">if</span> val.get() == <span class="number">0</span>:</span><br><span class="line">        label.configure(text=<span class="string">'radio 0'</span>)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        label.configure(text=<span class="string">'radio 1'</span>)</span><br><span class="line"></span><br><span class="line">label = tkinter.Label(root, text=<span class="string">'radio 0'</span>)</span><br><span class="line">label.pack()</span><br><span class="line">r0 = tkinter.Radiobutton(text = <span class="string">'radio0'</span>, variable = val, value = <span class="number">0</span>)</span><br><span class="line">r0.pack()</span><br><span class="line">r1 = tkinter.Radiobutton(text = <span class="string">'radio1'</span>, variable = val, value = <span class="number">1</span>)</span><br><span class="line">r1.pack()</span><br><span class="line">b = tkinter.Button(root, text=<span class="string">'button'</span>, command=func1)</span><br><span class="line">b.pack()</span><br><span class="line"></span><br><span class="line">root.mainloop()</span><br></pre></td></tr></table></figure>
<p><img src="https://s1.ax1x.com/2018/01/01/pSfgwq.md.gif" alt="实现"></p>
<h2 id="打包"><a href="#打包" class="headerlink" title="打包"></a>打包</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">C:\Users\bayi\Desktop\shiyan\progrem</span><br><span class="line">(venv) λ pip install pyinstaller</span><br><span class="line"></span><br><span class="line">C:\Users\bayi\Desktop\shiyan\progrem</span><br><span class="line">(venv) λ pyinstaller -F -w -i favicon.ico run.py</span><br></pre></td></tr></table></figure>
<blockquote>
<p>一开始因为代码中的设置ico图标为下面代码第一行<br>windows下打包路径识别有问题,把图标换到一个路径短的地方<br>修改成绝对路径就OK了(下面代码第二行,exe和ico要放在同一个目录下</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">self.baoxianTk.icobitmap(<span class="string">'favicon.ico'</span>)</span><br><span class="line"></span><br><span class="line">self.baoxianTk.iconbitmap(os.getcwd()+<span class="string">'/favicon.ico'</span>)</span><br></pre></td></tr></table></figure>
<h2 id="效果预览"><a href="#效果预览" class="headerlink" title="效果预览"></a>效果预览</h2><blockquote>
<p>虽然是现学现卖和对于别人的老知识，但是成功之后还是挺有成就感的(and我似乎对美工要求挑剔……..<br>调颜色和样式能挑半天,包括以前的那个爬虫的前端</p>
</blockquote>
<p><img src="https://s1.ax1x.com/2018/01/01/pSWjMj.jpg" alt="预览"></p>
<p>参考：<a href="http://www.360doc.com/content/12/0922/02/3234041_237501315.shtml" target="_blank" rel="noopener">Tkinter控件详解</a><br><a href="http://python.jobbole.com/85204/" target="_blank" rel="noopener">Python数据结构——栈</a><br><a href="http://www.bubuko.com/infodetail-1925713.html" target="_blank" rel="noopener">创建一个只能输入数字的输入框</a><br><a href="http://www.voidcn.com/article/p-hjlvsyxo-pt.html" target="_blank" rel="noopener">Tkinter教程之Entry篇</a><br><a href="http://mtunique.com/lambda_python/" target="_blank" rel="noopener">另一个Lambda表达式教程</a><br><a href="http://blog.chriscabin.com/coding-life/python/python-basic/1188.html" target="_blank" rel="noopener">《Python编程》笔记（七）</a></p>

      
    </div>

    
      
      



      
      
    

    
      <footer class="post-footer">
        
          <div class="post-tags">
            
              <a href="/tags/python/">python</a>
            
              <a href="/tags/tkinter/">tkinter</a>
            
          </div>
        
        
        
  <nav class="post-nav">
    
      <a class="prev" href="/2017/12/14/如何用PyQt写个通讯录/">
        <i class="iconfont icon-left"></i>
        <span class="prev-text nav-default">如何用PyQt5写个通讯录</span>
        <span class="prev-text nav-mobile">上一篇</span>
      </a>
    
    
      <a class="next" href="/2017/11/20/LCTF2017学到的姿势/">
        <span class="next-text nav-default">LCTF2017学到的姿势</span>
        <span class="prev-text nav-mobile">下一篇</span>
        <i class="iconfont icon-right"></i>
      </a>
    
  </nav>

      </footer>
    

  </article>


          </div>
          
  <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div> 
    </div>
  </div>


        </div>
      </main>

      <footer id="footer" class="footer">

  <div class="social-links">
    
      
        
          <a href="https://github.com/bay1" class="iconfont icon-github" title="github"></a>
        
      
    
      
        
          <a href="http://weibo.com/3190704711/profile?topnav=1&wvr=6&is_all=1" class="iconfont icon-weibo" title="weibo"></a>
        
      
    
      
    
      
    
      
    
    
    
  </div>


<div class="copyright">
  <span class="copyright-year">
    
    &copy; 
     
      2016 - 
    
    2018
    <span class="author">bay1</span>
  </span>
</div>
      </footer>

      <div class="back-to-top" id="back-to-top">
        <i class="iconfont icon-up"></i>
      </div>
    </div>

    
  
  <script type="text/javascript">
    var disqus_config = function () {
        this.page.url = 'https://bay1.top/2017/12/08/如何用Tkinter写个计算器/';
        this.page.identifier = '2017/12/08/如何用Tkinter写个计算器/';
        this.page.title = '如何用Tkinter写个计算器';
    };
    (function() {
    var d = document, s = d.createElement('script');

    s.src = '//https-blog-flywinky-top-1.disqus.com/embed.js';

    s.setAttribute('data-timestamp', +new Date());
    (d.head || d.body).appendChild(s);
    })();  
  </script>



    
  





  
    <script type="text/javascript" src="/lib/jquery/jquery-3.1.1.min.js"></script>
  

  
    <script type="text/javascript" src="/lib/slideout/slideout.js"></script>
  

  
    <script type="text/javascript" src="/lib/fancybox/jquery.fancybox.pack.js"></script>
  


    <script type="text/javascript" src="/js/src/even.js?v=2.6.0"></script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=2.6.0"></script>
<script src="/js/prettify.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 $('pre').addClass('prettyprint');
   prettyPrint();
 })
</script>
  </body>
</html>
